﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using NS.Utilities;
using WechatModel;
using HttpUtility;
using WechatUtility;
using NS.BLL.Systems;

namespace WechatDAL
{
    public partial class AccessTokenDal
    {
        /// <summary>
        /// 获取企业号的AccessToken
        /// </summary>
        /// <returns></returns>
        internal string GetEntToken()
        {
            return GetMetaConfig("EntToken");
        }

        /// <summary>
        /// 获取公众号的AccessToken
        /// </summary>
        /// <returns></returns>
        internal string GetPublicToken()
        {
            return GetMetaConfig("PublicToken");
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="key">表示公众号或服务号：带Public=公众号，带Ent=服务号</param>
        /// <returns></returns>
        private string GetMetaConfig(string key)
        {
            string AccessToken = DictionaryService.GetDicValue("微信参数","AccessToken");
            DateTime TimeOut = DateTime.Parse(DictionaryService.GetDicValue("微信参数","TokenTimeOut"));
            if (DateTime.Now >= TimeOut)  //如果已过期，则获取新的Token
            {
                AccessTokenInfo info = GetNewAccessToken(key);
                if (info != null)
                {
                    AccessToken = info.Access_token;
                    TimeOut = info.TimeOut;
                    DictionaryService.UpdateDicValue("微信参数", "AccessToken", AccessToken);
                    DictionaryService.UpdateDicValue("微信参数", "TokenTimeOut", TimeOut.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            return AccessToken;
        }

        /// <summary>
        /// 获取一个新的AccessToken
        /// </summary>
        /// <param name="key">表示公众号或服务号：PublicToken=公众号，EntToken=服务号</param>
        /// <returns></returns>
        private AccessTokenInfo GetNewAccessToken(string key)
        {
            string url = "";
            switch (key)
            {
                case "PublicToken":
                    url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WechatAPI4Public.AppID + "&secret=" + WechatAPI4Public.AppSecret + "&t=" + DateTime.Now.Ticks.ToString();
                    break;
                case "EntToken":
                    url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + WechatAPI4Ent.CorpID + "&corpsecret=" + WechatAPI4Ent.CorpSecret + "&t=" + DateTime.Now.Ticks.ToString();
                    break;
            }

            string result = Poster.DoGet(url);
            if (string.IsNullOrEmpty(result))
                return null;
            else
                return JsonHelper.JSON2T<AccessTokenInfo>(result);
        }
    }
}
